import {
  getPlantCapacityCalendarByPage,
  addPlantCapacityCalendar,
  updatePlantCapacityCalendar,
  delPlantCapacityCalendar,
  exportPlantCapacityCalendar,
  getAllProcess,
  getAllPlantCapacityCalendar,
  getPlantCapacityBase,
} from '@/services/product/plantCapacityCalendar';
import { PlusOutlined, AreaChartOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Tabs, Row, Col, Select } from 'antd';
import { DualAxes } from '@ant-design/charts';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { tabType } from './components/interfaceProduct';
const PlantCapacityCalendar: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);

  const [confirmLoading2, setConfirmLoading2] = useState(false); //统计图的disable
  const [modalVisit2, setModalVisit2] = useState(false); // 统计图
  const [optionsProcess, setoptionsProcess] = useState([]); //下拉框用到

  const [uvData, setuvData] = useState([]);
  const [transformData, settransformData] = useState([]);

  // 计划产能数据
  const planColumns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '柜体编号',
      dataIndex: 'batchProductCode',
    },
    {
      title: '工序名称',
      dataIndex: 'processName',
    },
    {
      title: '工序编号',
      dataIndex: 'processCode',
    },
    {
      title: '计划工时',
      dataIndex: 'workHour',
    },
    {
      title: '日期',
      dataIndex: 'date',
    },
    {
      title: '加工顺序编号',
      dataIndex: 'processSequence',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
  ];

  // 实际产能数据
  const actualColumns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '柜体编号',
      dataIndex: 'batchProductCode',
    },
    {
      title: '工序名称',
      dataIndex: 'processName',
    },
    {
      title: '工序编号',
      dataIndex: 'processCode',
    },
    {
      title: '实际工时',
      dataIndex: 'realWorkHour',
    },
    {
      title: '日期',
      dataIndex: 'date',
    },
    {
      title: '加工顺序编号',
      dataIndex: 'processSequence',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
  ];

  const handleSubmit = async (values: any) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addPlantCapacityCalendar(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updatePlantCapacityCalendar(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current!.reload();
  };

  const get_select = async () => {
    // 获取工序（下拉框）
    const getprocesslist = await getAllProcess(null);
    const processOptionContract = [];
    getprocesslist.data.map((item: any, index: any) => {
      processOptionContract.push({ value: item.id, label: item.processName });
    });
    setoptionsProcess(processOptionContract);
  };

  const dealwith_data = async () => {
    // 初始化柱状数据
    const theparam = {
      date: new Date().getTime(),
      processId: '',
      range: 10,
    };
    const columnardata = await getAllPlantCapacityCalendar(theparam);
    const thedata = [];
    columnardata.data.map((item: any, index: any) => {
      thedata.push({ time: item.date, value: item.capacityLoad });
    });
    setuvData(thedata);
  };

  const handleSubmit_data = async () => {
    const res = form.getFieldsValue();
    // 更新柱状数据
    const theparam = {
      date: new Date().getTime(),
      processId: res.process,
      range: res.date == undefined ? 10 : res.date,
    };
    const columnardata = await getAllPlantCapacityCalendar(theparam);
    const thedata = [];
    columnardata.data.map((item: any, index: any) => {
      thedata.push({ time: item.date, value: item.capacityLoad });
    });
    setuvData(thedata);
    // 更新横线数据
    const basicsdata = await getPlantCapacityBase({ processId: res.process });
    const thedata_basic = [];
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.normalCapacity,
        name: '正常产能',
      });
    });
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.overtimeCapacity,
        name: '加班产能',
      });
    });
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({ time: item.date, count: basicsdata.data.totalCapacity, name: '总产能' });
    });
    settransformData(thedata_basic);
  };

  const config = {
    data: [uvData, transformData],
    xField: 'time',
    yField: ['value', 'count'],
    geometryOptions: [
      {
        geometry: 'column',
        columnWidthRatio: 0.4,
      },
      {
        geometry: 'line',
        seriesField: 'name',
      },
    ],
  };

  const handleCancel = async () => {
    setModalVisit2(false);
    setuvData([]);
    settransformData([]);
  };

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '计划产能',
      content: (
        <div>
          <ProTable
            headerTitle="计划产能查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              labelWidth: 100,
              defaultCollapsed: true,
            }}
            toolBarRender={(action, { selectedRows }) => [
              // <Button
              //   key="button"
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     setCreateOrUpdate(false);
              //     setFormTitle('新建');
              //     form.resetFields();
              //     setModalVisit(true);
              //   }}
              //   type="primary"
              // >
              //   新建
              // </Button>,
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filters = filterTran(ref.current.getFieldsValue());
                  exportPlantCapacityCalendar({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `PlantCapacityCalendar.xlsx`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTran(params);
              const result = await getPlantCapacityCalendarByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={planColumns}
            scroll={{ x: 1000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '实际产能',
      content: (
        <div>
          <ProTable
            headerTitle="实际产能查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              labelWidth: 100,
              defaultCollapsed: true,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<AreaChartOutlined />}
                onClick={async () => {
                  get_select();
                  dealwith_data();
                  setFormTitle('产能统计图');
                  form.resetFields();
                  setModalVisit2(true);
                }}
                type="primary"
              >
                产能统计图
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTran(params);
              const result = await getPlantCapacityCalendarByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={actualColumns}
            scroll={{ x: 1000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <div className="box">
        <Tabs
          type="card"
          items={tabList.map((item, i) => {
            const id = String(i + 1);
            return {
              label: item.label,
              key: id,
              children: <div>{item.content}</div>,
            };
          })}
        />
      </div>
      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="batchProductCode"
          label="柜体编号"
          rules={[{ required: true, message: 'Please input your batchProductCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="batchProductId"
          label="柜体ID"
          rules={[{ required: true, message: 'Please input your batchProductId!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="date"
          label="日期"
          rules={[{ required: true, message: 'Please input your date!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="factoryCode"
          label="加工车间Code"
          rules={[{ required: true, message: 'Please input your factoryCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="factoryId"
          label="加工车间ID"
          rules={[{ required: true, message: 'Please input your factoryId!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="memo"
          label="备注"
          rules={[{ required: true, message: 'Please input your memo!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="processCode"
          label="加工工序编号"
          rules={[{ required: true, message: 'Please input your processCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="processId"
          label="工序ID"
          rules={[{ required: true, message: 'Please input your processId!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="processName"
          label="加工工序名称"
          rules={[{ required: true, message: 'Please input your processName!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="processSequence"
          label="加工顺序编号"
          rules={[{ required: true, message: 'Please input your processSequence!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="workHour"
          label="工时"
          rules={[{ required: true, message: 'Please input your workHour!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="factoryName"
          label="车间描述"
          rules={[{ required: true, message: 'Please input your factoryName!' }]}
          disabled={createOrUpdate}
        />
      </ModalForm>
      <Modal
        title="产能统计"
        width={900}
        visible={modalVisit2}
        confirmLoading={confirmLoading2}
        onCancel={handleCancel}
        footer={[
          <Button key="back" onClick={() => handleCancel()}>
            关闭
          </Button>,
        ]}
        destroyOnClose
      >
        <Form
          name="wrap"
          // labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          // wrapperCol={{ flex: 1 }}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          colon={false}
        >
          <Row justify="center" gutter={[50, 0]}>
            <Col span={10}>
              <Form.Item label="时间" name="date">
                <Select
                  placeholder="请选择时间"
                  onChange={(value) => {}}
                  options={[
                    { value: '10', label: '10' },
                    { value: '20', label: '20' },
                    { value: '30', label: '30' },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={10}>
              <Form.Item name="process" label="班组">
                <Select
                  placeholder="请选择班组"
                  onChange={(value) => {}}
                  options={optionsProcess}
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Button
                type="primary"
                onClick={() => {
                  handleSubmit_data();
                }}
              >
                确定
              </Button>
            </Col>
          </Row>
        </Form>
        {/* 统计图 */}
        <div className="down">
          <DualAxes {...config} />
        </div>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default PlantCapacityCalendar;
